package cn.micro.core.util;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;

public class AesUtil {

    /**
     * 算法/模式/填充
     */
    private static final String CIPHER_ECB_INSTANCE = "AES/ECB/PKCS5Padding";

    /**
     * 算法/模式/填充
     */
    private static final String CIPHER_CBC_INSTANCE = "AES/CBC/PKCS5Padding";
    /**
     * 初始化 iv 16位
     */
    public static final String DEFAULT_IV = "BALGEALG12345678";


    /**
     * AES key的默认长度
     */
    private static int keyLength = 16;
    /**
     * 编码模式-UTF-8
     */
    private static final String ENCODE = "utf-8";

    /**
     * 编码算法AES
     */
    private static final String ENCYPT_AES = "AES";

    /**
     * 初始化key16位
     */
    public static final String DEFAULT_KEY = "BALGEALG12345678";

    /**
     * 将二进制转换成16进制
     *
     * @param buf
     * @return
     */
    public static String parseByte2HexStr(byte buf[]) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < buf.length; i++) {
            String hex = Integer.toHexString(buf[i] & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            sb.append(hex.toUpperCase());
        }
        return sb.toString();
    }


    /**
     * 将16进制转换为二进制
     *
     * @param hexStr
     * @return
     */
    public static byte[] parseHexStr2Byte(String hexStr) {
        if (hexStr.length() < 1) {
            return null;
        }
        byte[] result = new byte[hexStr.length() / 2];
        for (int i = 0; i < hexStr.length() / 2; i++) {
            int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
            int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16);
            result[i] = (byte) (high * 16 + low);
        }
        return result;
    }

    private static String getOriginalString(String sSrc, Cipher cipher) {
        try {
            byte[] original = cipher.doFinal(parseHexStr2Byte(sSrc));
            String originalString = new String(original, ENCODE);
            return originalString;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static SecretKeySpec generateMySQLAESKey(final String key, final String encoding) {
        try {
            final byte[] finalKey = new byte[16];
            int i = 0;
            for (byte b : key.getBytes(encoding))
                finalKey[i++ % 16] ^= b;
            return new SecretKeySpec(finalKey, ENCYPT_AES);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 用默认的key加密
     *
     * @param sSrc
     * @return
     * @throws Exception
     */
    public static String encrypt(String sSrc) {
        if (DEFAULT_KEY == null) {
            log.info("key为空！");
            return null;
        }
        // 判断Key是否为16位
        if (DEFAULT_KEY.length() != keyLength) {
            log.info("Key长度不是16位");
            return null;
        }
        byte[] encrypted = new byte[0];
        try {
            SecretKeySpec skeySpec = generateMySQLAESKey(DEFAULT_KEY, ENCODE);
            //"算法/模式/补码方式"
            Cipher cipher = Cipher.getInstance(CIPHER_INSTANCE);
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
            // cbc 加密传参
            // cipher.init(Cipher.ENCRYPT_MODE, skeySpec, ivspec);
            encrypted = cipher.doFinal(sSrc.getBytes(ENCODE));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        }
        //此处转为16进制字符串
        return parseByte2HexStr(encrypted);
    }

    /**
     * 用默认的key解密
     *
     * @param sSrc
     * @return
     * @throws Exception
     */
    public static String decrypt(String sSrc) {
        try {
            // 判断Key是否正确
            if (DEFAULT_KEY == null) {
                System.out.print("Key为空null");
                return null;
            }
            // 判断Key是否为16位
            if (DEFAULT_KEY.length() != keyLength) {
                System.out.print("Key长度不是16位");
                return null;
            }
            SecretKeySpec skeySpec = generateMySQLAESKey(DEFAULT_KEY,ENCODE);
            Cipher cipher = Cipher.getInstance(CIPHER_INSTANCE);
            cipher.init(Cipher.DECRYPT_MODE, skeySpec);
            // cbc 加密传参
            // cipher.init(Cipher.DECRYPT_MODE, skeySpec, ivspec);
            return getOriginalString(sSrc, cipher);
        } catch (Exception ex) {
            log.info(ex.toString());
            return null;
        }
    }


}
